#ifndef __SHARE_HPP__
#define __SHARE_HPP__

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstring>
#include <unistd.h>
#include "log.hpp"

Log log;

#define SIZE_MM 4096
#define MODE 0666
#define MYFIFO_PATH "./myfifo"
const std::string pathname = "/home/ocean";
const int porj_id = 123;


void DeleteShare(int shmid)
{
    int ret = shmctl(shmid, IPC_RMID, nullptr);
    if (ret == -1)
    {
        log(error, "delete share_mm failure: %s", strerror(errno));
        exit(3);
    }
    log(info, "delete share_mm success");
}


key_t GetKey()
{
    key_t key = ftok(pathname.c_str(), porj_id);
    if (key < 0)
    {
        log(fatal, "ftok failure:%s", strerror(errno));
        return 1;
    }
    log(info, "GetKey success");
    return key;
}


int GetShare_mm(int flag)
{

    int shmid = shmget(GetKey(), SIZE_MM, flag);
    if (shmid == -1)
    {
        log(fatal, "shmget failure: %s", strerror(errno));
        return 2;
    }
    log(info, "shmget success");
    return shmid;
}

int CreateShmid()
{
    return GetShare_mm(IPC_CREAT | IPC_EXCL | MODE);
}


int Getshmid()
{
    return GetShare_mm(IPC_CREAT);
}


key_t Get_key()
{
    return GetKey();
}



//管道

class FIFO
{
public:
    FIFO()
    {
        int n = mkfifo(MYFIFO_PATH,MODE);
        if(n == -1)
        {
            log(fatal,"mkfifo failure: %s",strerror(errno));
            exit(4);
        }
        log(info,"mkfifo success");
    }

    ~FIFO()
    {
        int n = unlink(MYFIFO_PATH);
        if(n == -1)
        {
            log(error,"unlink failure: %s",strerror(errno));
            exit(4);
        }
        log(info,"unlink success");
    }
};

#endif
